<template>
  <t-form
    ref="searchFormRef"
    :data="formData"
    :label-width="searchConfig.labelWidth || '80px'"
    resetType="initial"
    layout="inline"
  >
    <template v-for="item in searchConfig.formItems" :key="item.prop">
      <t-form-item :label="item.label" :name="item.prop" :label-width="item.labelWidth">
        <t-input
          v-if="item.type === 'input'"
          v-model="formData[item.prop]"
          :placeholder="item.placeholder"
        ></t-input>
        <t-select
          v-if="item.type === 'select'"
          v-model="formData[item.prop]"
          :options="item.options"
          :placeholder="item.placeholder"
          clearable
        >
        </t-select>
        <t-date-picker
          v-if="item.type === 'datePicker'"
          v-model="formData[item.prop]"
          :enable-time-picker="item.enableTimePicker"
          allow-input
          clearable
          format="YYYY-MM-DD a hh:mm:ss"
        />
        <t-date-range-picker
          v-if="item.type === 'dateRangePicker'"
          v-model="formData[item.prop]"
          allow-input
          clearable
          :enable-time-picker="item.enableTimePicker"
        />
        <t-cascader
          v-if="item.type === 'cascader'"
          v-model="formData[item.prop]"
          :options="item.options"
          :show-all-levels="false"
          trigger="hover"
          clearable
        />
      </t-form-item>
    </template>
    <t-form-item>
      <t-button theme="primary" style="margin-right: 10px" @click="emit('search', formData)"
        >搜索</t-button
      >
      <t-button theme="default" @click="reset">重置</t-button>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'

const props = defineProps<{
  searchConfig: {
    pageName: string
    labelWidth?: string
    formItems: any[]
  }
}>()

// 定义form的数据
const initForm: any = {}
for (const item of props.searchConfig.formItems) {
  if (item.prop) initForm[item.prop] = item.initValue ?? null
}

const emit = defineEmits(['search'])
const formData = reactive(initForm)

const searchFormRef = ref()
const reset = () => {
  searchFormRef.value.reset()
  emit('search', formData)
}

defineExpose({
  formData
})
</script>
